package cn.edu.zjgsu.ito.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

import cn.edu.zjgsu.ito.dao.UserInfomationMapper;
import cn.edu.zjgsu.ito.dao.UserLoginMapper;
import cn.edu.zjgsu.ito.dao.UserScoreMapper;
import cn.edu.zjgsu.ito.exception.PwdWrongException;
import cn.edu.zjgsu.ito.exception.UserInexistException;
import cn.edu.zjgsu.ito.model.UserInfomation;
import cn.edu.zjgsu.ito.model.UserLogin;
import cn.edu.zjgsu.ito.model.UserLoginExample;
import cn.edu.zjgsu.ito.model.UserScore;
import cn.edu.zjgsu.ito.service.UserLoginServiceI;
import cn.edu.zjgsu.ito.util.ConstantMethod;
import cn.edu.zjgsu.ito.vo.UserLoginOkVo;
import cn.edu.zjgsu.ito.vo.UserLoginVo;

@Service("userLoginService")
public class UserLoginServiceImpl implements UserLoginServiceI {

    static final String product = "Dysmsapi";
    static final String domain = "dysmsapi.aliyuncs.com";
    static final String accessKeyId = "LTAIrH7584qKnUmP";
    static final String accessKeySecret = "KE6GZc7efhIOeSr7di8FO0KckEgpwG";
	
	
	@Autowired
	private UserLoginMapper userLoginMapper;
	
	@Autowired
	private UserInfomationMapper userInfomationMapper;
	
	@Autowired
	private UserScoreMapper userScoreMapper;
	
	@Override
	public UserLoginOkVo userLogin(UserLoginVo userLoginVo) {
		UserLoginOkVo userLoginOkVo = new UserLoginOkVo();
		UserLoginExample userLoginExample = new UserLoginExample();
	
		userLoginExample.or().andUsernameEqualTo(userLoginVo.getUsername());
		
		List<UserLogin> user = userLoginMapper.selectByExample(userLoginExample);
		
		if(user.size() > 0){
			if(user.get(0).getPassword().equals(userLoginVo.getPassword())){
				userLoginOkVo.setUserState(user.get(0).getUserState());
				userLoginOkVo.setUserId(user.get(0).getUserId());
				return userLoginOkVo;
			}else{
				throw new PwdWrongException();
			}
		}else{
			throw new UserInexistException();
		}
	}

	@Override
	public String loginSendMessage(String username) {
		
		UserLoginExample userLoginExample = new UserLoginExample();
		userLoginExample.or().andUsernameEqualTo(username);
		List<UserLogin> userLogin = userLoginMapper.selectByExample(userLoginExample);
		if(userLogin.size() > 0){
			String code = ConstantMethod.getSixNumberCode();
			try {
				sendSms(username,code);
				return code;
			} catch (ClientException e) {
				e.printStackTrace();
				return "error";
			}
		}else{
			return "error";
		}
	}
	
	public SendSmsResponse sendSms(String phone,String msg) throws ClientException {

        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号1
        request.setPhoneNumbers(phone);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName("随手快递注册测试");
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode("SMS_78745175");
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        request.setTemplateParam("{\"code\":\"" + msg + "\"}");

        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);

        return sendSmsResponse;
    }

	@Override
	public int loginMessage(String username, String securitySession,
			String security) {

		if(securitySession.equals(security)){
			UserLoginExample userLoginExample = new UserLoginExample();
			userLoginExample.or().andUsernameEqualTo(username);
			List<UserLogin> userLogin = userLoginMapper.selectByExample(userLoginExample);
			if(userLogin.size() > 0){
				if(userLogin.get(0).getUserState() == 1){
					return userLogin.get(0).getUserId();
				}
			}
		}
		return -1;
	}

	@Override
	public String registerPhone(String phone) {
		UserLoginExample userLoginExample = new UserLoginExample();
		userLoginExample.or().andUsernameEqualTo(phone);
		List<UserLogin> userLogin = userLoginMapper.selectByExample(userLoginExample);
		if(userLogin.size() > 0){
			return "error";
		}else {
			try {
				String code = ConstantMethod.getSixNumberCode();
				sendSms(phone,code);
				return code;
			} catch (ClientException e) {
				e.printStackTrace();
				return "error";
			}
		}
	}

	@Override
	public int registerSuccess(String username,String password) {

		UserLogin userLogin = new UserLogin();
		userLogin.setUsername(username);
		userLogin.setPassword(password);
		userLogin.setUserState(1);
		userLoginMapper.insertSelective(userLogin);
		int userId = userLogin.getUserId();
		
		UserInfomation userInfomation = new UserInfomation();
		userInfomation.setUserId(userId);
		userInfomation.setNickname("用户" + username.substring(7,11));
		userInfomation.setSex("男");
		userInfomation.setSignature("这个人很懒，什么人都没有留下。");
		userInfomation.setHeadPortraitUrl("/randomdelivery/mobile/image/defaultavatar.png");
		userInfomationMapper.insertSelective(userInfomation);
		
		UserScore userScore = new UserScore();
		userScore.setUserId(userId);
		userScore.setCreditScore(80);
		userScore.setIntegralScore(80);
		userScoreMapper.insertSelective(userScore);
		
		return userId;
	}

}
